using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using Sucrose.Base;
using Sucrose;

namespace SucroseTray
{
    public partial class frmMain : Form
    {   
        private VoidDelegate EnableControls;
        private VoidDelegate DisableControls;

        private BackgroundWorker bwWorker;

        private bool isDone = true;
        private int interval = 60;
        private delegate void VoidDelegate();

        public frmMain()
        {
            InitializeComponent();
            lblCurrentTask.Text = "";
            progressBar.Maximum = 100;

            EnableControls = new VoidDelegate(ReEnable);
            DisableControls = new VoidDelegate(LockDown);

            // Set up the BackgroundWorker we use to do all our work
            bwWorker = new SucroseWorker();

            // Assign WorkerCompleted and ProgressUpdated
            bwWorker.RunWorkerCompleted += bw_RunWorkerCompleted;
            bwWorker.ProgressChanged += bw_ProgressChanged;
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            SucroseControl control = SucroseControl.GetInstance();

            this.trayIcon.Visible = true;

            this.interval = control.UpdateInterval;

            this.chkAutoUpdate.Checked = control.AutoUpdate;
            this.chkDownloadSupportDocs.Checked = control.DownloadSupportDocuments;
            this.chkDownloadTaskDocs.Checked = control.DownloadTaskDocuments;
            this.chkImportGrades.Checked = control.ImportGrades;
            this.chkImportTasks.Checked = control.ImportTasks;

            this.refreshTimer_Tick(this, null);
            this.refreshTimer.Interval = interval * 60 * 1000;
            this.txtInterval.Text = interval.ToString();

            this.lblCurrentTask.Text = "Ready.";
        }

        private void trayIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
        }

        private void btnManual_Click(object sender, EventArgs e)
        {
            Invoke(DisableControls);
            bwWorker.RunWorkerAsync();
        }

        private void frmMain_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();
            }
        }

        private void refreshTimer_Tick(object sender, EventArgs e)
        {
            if (Settings.GetIntegerValueForKey("AutoUpdate") == 1 && e != null)
            {
                btnManual_Click(this, null);
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            SucroseControl control = SucroseControl.GetInstance();
            int oldInterval = interval;

            try
            {
                interval = Int32.Parse(txtInterval.Text);
                Settings.SetValueAtKey("UpdateInterval", txtInterval.Text);
            }
            catch(IndexOutOfRangeException)
            {
                interval = oldInterval;
                txtInterval.Text = oldInterval.ToString();
                MessageBox.Show("The update interval must be greater than 5 minutes.", "Update Interval Too Short", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            catch(FormatException)
            {
                txtInterval.Text = oldInterval.ToString();
                interval = oldInterval;
                MessageBox.Show("The Update interval must be an integer greater than 5", "Update Interval badly Formatted", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            refreshTimer.Interval = interval * 60 * 1000;

            control.AutoUpdate = chkAutoUpdate.Checked;
            control.DownloadSupportDocuments = chkDownloadSupportDocs.Checked;
            control.DownloadTaskDocuments = chkDownloadTaskDocs.Checked;
            control.ImportGrades = chkImportGrades.Checked;
            control.ImportTasks = chkImportTasks.Checked;
        }

        private void ReEnable()
        {
            this.txtInterval.Enabled = true;
            this.chkAutoUpdate.Enabled = true;
            this.chkDownloadSupportDocs.Enabled = true;
            this.chkDownloadTaskDocs.Enabled = true;
            this.chkImportGrades.Enabled = true;
            this.chkImportTasks.Enabled = true;
            this.btnManual.Enabled = true;
            this.btnSave.Enabled = true;
        }

        private void LockDown()
        {
            this.txtInterval.Enabled = false;
            this.chkAutoUpdate.Enabled = false;
            this.chkDownloadSupportDocs.Enabled = false;
            this.chkDownloadTaskDocs.Enabled = false;
            this.chkImportGrades.Enabled = false;
            this.chkImportTasks.Enabled = false;
            this.btnManual.Enabled = false;
            this.btnSave.Enabled = false;
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(!isDone)
                e.Cancel = true;
        }

        private void lnkHelp_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start("http://code.google.com/p/sucrose");
            }
            catch (Exception)
            {
                MessageBox.Show("Could not open http://code.google.com/p/sucrose");
            }
        }

        private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            lblCurrentTask.Text = e.UserState.ToString();
            progressBar.Value = e.ProgressPercentage;
        }

        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Invoke(EnableControls);

            if (e.Error != null && Util.CheckNetworkConnection())
                MessageBox.Show(this, e.Error.Message, "Sucrose Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}